
import React, { PureComponent, Component } from 'react';
import { BasicPagination, isInvalidObject, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../../../components/TableCustomize'
import { Row, Col, Form, Select, Layout, Upload, Button, InputNumber, Table, Input, Alert, Spin, Modal, Drawer, Divider, Icon, Badge, PageHeader, Tabs, Card } from 'antd';

import { BasicLayout, BasicLayoutSearch } from '../../../../components/BasicLayout'
import { withRouter } from 'react-router';
import * as ProcessQualityControlService from '../../../../axios/ProcessQualityControl'
import * as APIServiceFile from '../../../../axios/File'
import EditTable from '../../../../components/EditTable';
import DetailsForm from './Components/DetailsForm'
import ResultForm from './Components/ResultForm'
const { confirm } = Modal;

const FormItem = Form.Item;
const { Header, Footer, Sider, Content } = Layout;
const { Option } = Select


class Parallel extends Component {
    state = {
        type: '哥林柱与机架导轨面平行度记录表',
        data: {},
        dataSource: [],
        dataSource1: [],
        dataSource2: [],
        columns: [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                align: 'center',
                ellipsis: true,
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '测量位置',
                dataIndex: 'measuringPoint',
                sorter: (a, b) => compareString(a.measuringPoint, b.measuringPoint),
                width: 100,
                ellipsis: true,
            },
            {
                title: '平行度要求标准',
                dataIndex: 'standard',
                sorter: (a, b) => compareString(a.standard, b.standard),
                width: 150,
                ellipsis: true,
            },
            {
                title: '实测数据(mm)',
                dataIndex: 'message1',
                sorter: (a, b) => compareString(a.message1, b.message1),
                width: 200,
                ellipsis: true,
                editable: true,
            },
            {
                title: '平行度值（Max-Min）',
                dataIndex: 'message2',
                sorter: (a, b) => compareString(a.message2, b.message2),
                width: 230,
                ellipsis: true,
                editable: true,
            },
            { dataIndex: 'opts', },
        ],
        isEdit: false,   // true 可编辑  false 不可编辑
        queryForm: {},
        formData: {},
        searchItem: {},
        loading: false,
        spinning: false,
        previewVisible: false,
        previewImage: '',
        file: {},
        visible: false,
    }
    componentDidMount() {
        let data = {}, dataSource = [], imgList = [], formData = {}, dataSource1 = [], dataSource2 = [], file = {}, searchItem = {}
        if (this.props.location?.data) {
            data = this.props.location?.data
        } else {
            data = JSON.parse(localStorage.getItem('ProcessQualityControl_Parallel'))
        }
        dataSource = data.dataSource
        formData = data.formData
        imgList = data.imgList
        searchItem = data.searchItem
        for (let item of dataSource) {
            if (item.type == '操作侧下方哥林柱') {
                dataSource1 = item.data
            } else if (item.type == '反操作侧下方哥林柱') {
                dataSource2 = item.data
            }
        }
        if (imgList && imgList.length > 0) {
            file.imgName = imgList[0].imgName
            file.imgId = imgList[0].imgId
        } else {
            file.imgName = ''
            file.imgId = ''
        }
        this.setState({ data, formData, dataSource, dataSource1, dataSource2, file, searchItem }, () => {
            // 查询图片 URL
            this.queryFileId(file.imgId)
        })
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    // table上直接修改数据
    loadData = (value, dataSource) => {
        console.log('在表格修改数据后保存的数据:', value, dataSource);
    }
    // 点击编辑按钮
    handleEdit = () => {
        console.log('编辑');
        this.setState({ isEdit: true })
    }
    getTableData = (data, row) => {
        for (let key in row) {
            let arr = key.split('_')
            const index = data.findIndex(item => {
                return arr[1] == item.id
            });
            if (index > -1) {
                const item = data[index];
                data.splice(index, 1, {
                    ...item,
                    [arr[0]]: row[key],
                });
            } else {
                data.push(row);
            }
        }
        return data
    }
    // 保存
    handleSave = () => {
        let data = [], isInPlant
        // 获取 表格1 数据
        this.editTable1.validateFields((error, row) => {
            if (error) {
                return;
            }
            console.log(row, 'editTable1');
            const newData1 = [...this.state.dataSource1];
            let dataSource1 = this.getTableData(newData1, row)
            data = [...data, ...dataSource1]

            this.setState({ dataSource1 });
        });
        // 获取 表格2 数据
        this.editTable2.validateFields((error, row) => {
            if (error) {
                return;
            }
            console.log(row, 'editTable2');
            const newData2 = [...this.state.dataSource2];
            let dataSource2 = this.getTableData(newData2, row)
            data = [...data, ...dataSource2]
            this.setState({ dataSource2 });
        });
        // 获取基础信息
        this.DetailForm.validateFields((error, value) => {
            if (error) {
                return;
            }
            console.log(value, '获取基础信息');
            isInPlant = value.isInPlant
        });
        // 获取结论信息
        // this.resultForm.validateFields((error, value) => {
        //     if (error) {
        //         return;
        //     }
        //     console.log(value, '获取结论信息');
        // });
        console.log(data, isInPlant, 'data, isInPlant');
        let dto = {
            data, isInPlant,
            qualityStandardId: this.state.formData?.id,
            userId: localStorage.getItem('userId')
        }
        this.updateDetails(dto)
        this.setState({ isEdit: false }, () => {
            let oldData = this.state.data
            const { dataSource1, dataSource2, formData } = this.state
            formData.isInPlant = isInPlant

            for (let item of oldData.dataSource) {
                if (item.type == '操作侧下方哥林柱') {
                    item.data = dataSource1
                } else if (item.type == '反操作侧下方哥林柱') {
                    item.data = dataSource2
                }
            }
            oldData.formData = formData
            localStorage.removeItem('ProcessQualityControl_Parallel')
            localStorage.setItem('ProcessQualityControl_Parallel', JSON.stringify(oldData))
        })
    };
    // 修改详情
    updateDetails = (dto) => {
        ProcessQualityControlService.updateDetails(dto).then(res => {
            if (res.data.code != 200) {
                openModalMessage('warning', res.data.msg)
                return
            }
            openSuccessModal(res.data.msg)
            this.setState({ isEdit: false })
        })
    }
    // 点击取消按钮
    handleCancel = () => {
        this.setState({ isEdit: false })
    }

    // 打开详情页
    openDetails = () => {
        const { dataSource1, dataSource2, formData, type, file } = this.state
        let data = { title: type, queryForm: { dataSource1, dataSource2, formData, file }, path: 'ProcessQualityControl_Parallel' }
        localStorage.setItem('Parallel_Report', JSON.stringify(data))
        this.props.history.push({ pathname: "/Parallel_Report", data })
    }

    // 根据文件ID查询详情
    queryFileId = async (id) => {
        const { file } = this.state
        await APIServiceFile.queryFileId(id).then(res => {
            if (res.data.code != 200) {
                openModalMessage('error', res.data.data.msg)
                return
            }
            let data = res.data.data
            file.imgUrl = data?.tomcatPath || ''
            this.setState({ file })
        })
    }
    // 预览图片
    showPicture = (url) => {
        this.setState({ previewImage: url, previewVisible: true })
    }
    render() {
        const { form: { getFieldDecorator } } = this.props;
        const { searchItem, isEdit, file, loading, type, spinning, formData, previewVisible, previewImage, columns, dataSource1, dataSource2, } = this.state

        const titleStyle = { fontWeight: 'bold', fontSize: 14 }

        return (
            <Spin spinning={spinning}>
                <BasicLayoutSearch>
                    <PageHeader
                        style={{ padding: '4px 24px' }}
                        onBack={() => this.props.history.push({ pathname: '/ProcessQualityControl', data: { searchItem } })}
                        extra={
                            <div style={{ display: 'flex', justifyContent: 'end' }}>
                                {
                                    isEdit ? null : <div style={{ display: 'flex', justifyContent: 'end' }}><Button type='primary' onClick={this.handleEdit} style={{ width: 65 }}>编辑</Button></div>
                                }
                                {
                                    isEdit ?
                                        <div style={{ display: 'flex', justifyContent: 'end' }}>
                                            <Button type='default' onClick={this.handleCancel} style={{ width: 65 }}>取消</Button>&emsp;
                                            <Button type='primary' onClick={this.handleSave} style={{ width: 65 }}>保存</Button>
                                        </div>
                                        : null
                                }
                                &emsp;<Button type='primary' icon='eye' onClick={this.openDetails}>查看报表</Button>
                            </div>
                        }
                        title={type}>
                    </PageHeader>
                </BasicLayoutSearch>
                <Layout className="layout-model">
                    <DetailsForm
                        title='基础信息'
                        ref={node => this.DetailForm = node}
                        formData={formData}
                        isEdit={isEdit}
                        titleStyle={titleStyle}
                    />
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>操作侧下方哥林柱</div>}
                        bordered={false}>
                        <EditTable
                            dataSource={dataSource1}
                            columns={columns}
                            ref={node => (this.editTable1 = node)}
                            rowKey={(record) => record.id}
                            isEdit={isEdit}
                            pagination={false}
                            allowDrafting={true}
                            allowEditable={this.loadData}
                            loading={loading}
                            scroll={{ y: 200, x: 500 }}
                        />
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>反操作侧下方哥林柱</div>}
                        bordered={false}>
                        <EditTable
                            dataSource={dataSource2}
                            columns={columns}
                            ref={node => (this.editTable2 = node)}
                            rowKey={(record) => record.id}
                            isEdit={isEdit}
                            pagination={false}
                            allowDrafting={true}
                            allowEditable={this.loadData}
                            loading={loading}
                            scroll={{ y: 200, x: 500 }}
                        />
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>图片</div>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col span={7}>
                                <div style={{ height: 200, width: '100%', textAlign: 'center', lineHeight: '200px', border: '1px solid #e8e8e8', color: '#c3c2c2', fontSize: 17 }}>
                                    <img width={'100%'} height={190} src={file?.imgUrl} onClick={() => this.showPicture(file?.imgUrl)}></img>
                                </div>
                                <Input placeholder='请输入图片名称' value={file?.imgName} disabled allowClear style={{ textAlign: 'center' }} />
                            </Col>
                        </Row>
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <ResultForm
                        titleStyle={titleStyle}
                        title='结论信息'
                        formData={formData}
                        isEdit={isEdit}
                        ref={node => (this.resultForm = node)}
                    />
                </Layout>

                {/* 预览图片 */}
                <Modal visible={previewVisible} footer={null} onCancel={() => this.setState({ previewVisible: false, previewImage: '' })}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </Spin>
        )
    }
}

export default Form.create()(withRouter(Parallel));